#include "sklcc_api.h"
#include "memop_id.h"

#include "OpenDPI_demo.h"

#include <stdio.h>
#include <assert.h>
#include <malloc.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stdarg.h>

extern u32 ipoque_detection_get_sizeof_ipoque_id_struct(void);
extern void* get_id(const struct osdpi_ip_addr *ip);

static u32 memop_osdpi_ids_init(struct osdpi_id* osdpi_ids,u32 idNum)
{
	if(idNum <= 0 || idNum > MAX_OSDPI_IDS)
		return 1;
	assert(osdpi_ids != NULL);

	//Warning:idNum may be larger than real id number.
	u32 size_id_struct = ipoque_detection_get_sizeof_ipoque_id_struct();
	u32 id_index = 0;
	for(id_index = 0;id_index < idNum;id_index++)
	{
		memset(&osdpi_ids[id_index],0,sizeof(struct osdpi_id));
		osdpi_ids[id_index].ipoque_id = calloc(1,size_id_struct);
		assert(osdpi_ids[id_index].ipoque_id != NULL);
	}

	return 0;
}

extern u32 memop_osdpi_ids_free(struct osdpi_id* osdpi_ids,u32 idNum)
{
	assert(osdpi_ids != NULL);
	//Warning:idNum may be larger than real id number.
	//in demo version,idNum == MAX_OSDPI_IDS
	if(idNum <= 0 || idNum > MAX_OSDPI_IDS)
		return 1;
	
	u32 id_index = 0;
	for(id_index = 0;id_index < idNum;id_index++)
	{
		assert(osdpi_ids[id_index].ipoque_id != NULL);
		free(osdpi_ids[id_index].ipoque_id);
		osdpi_ids[id_index].ipoque_id = NULL;
	}	
	free(osdpi_ids);
	osdpi_ids = NULL;

	return 0;
}

extern struct osdpi_id* memop_osdpi_ids_create(u32 idNum)
{
	if(idNum <= 0 || idNum > MAX_OSDPI_IDS)
		return NULL;
	struct osdpi_id *osdpi_ids = NULL;

	osdpi_ids = malloc(idNum * sizeof(struct osdpi_id));
	assert(osdpi_ids != NULL);

	memop_osdpi_ids_init(osdpi_ids,idNum);
	assert(osdpi_ids != NULL);

	return osdpi_ids;
}

extern void* memop_get_id(const struct osdpi_ip_addr *ip)
{
	assert(ip != NULL);
	return get_id(ip);
}
